package handler

import (
	"context"
	"errors"
	"user-srv/basic/globar"
	"user-srv/model"
	"user-srv/pkg"

	__ "user-srv/basic/proto"
)

type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	var u model.User
	u.Mobile = in.Mobile
	u.Password = pkg.Md5(in.Password)
	if err := u.GetOneFile(globar.DB); err != nil {
		return nil, errors.New("参数获取失败" + err.Error())
	}
	if u.ID != 0 {
		return nil, errors.New("查询失败")
	}
	if err := u.Create(globar.DB); err != nil {
		return nil, errors.New("注册失败" + err.Error())
	}
	return &__.RegisterResp{
		Id: int64(u.ID),
	}, nil
}

// 视频发布
func (s *Server) Videoadd(_ context.Context, in *__.VideoaddReq) (*__.VideoaddResp, error) {
	var v model.Video
	v = model.Video{
		Title:  in.Title,
		Url:    in.Url,
		Num:    int(in.Num),
		Info:   in.Info,
		Status: int(in.Status),
		Types:  int(in.Types),
		Image:  in.Image,
	}
	if err := v.GetOnfile(globar.DB); err != nil {
		return nil, errors.New("参数获取失败" + err.Error())
	}
	if v.ID != 0 {
		return nil, errors.New("查询失败")
	}
	if err := v.Create(globar.DB); err != nil {
		return nil, errors.New("注册失败" + err.Error())
	}
	return &__.VideoaddResp{
		Id: int64(v.ID),
	}, nil
}

// 视频分页查询
func (s *Server) Videolist(_ context.Context, in *__.VideolistReq) (*__.VideolistResp, error) {
	var v model.Video
	cover, err := v.GetCover(globar.DB, int(in.Page), int(in.Size))
	if err != nil {
		return nil, err
	}
	return &__.VideolistResp{
		List: cover,
	}, nil
}

// 视频模糊查询
func (s *Server) Videolike(_ context.Context, in *__.VideolikeReq) (*__.VideolikeResp, error) {
	var v model.Video
	err := v.GetLike(globar.DB, in.Title)
	if err != nil {
		return nil, err
	}
	return &__.VideolikeResp{
		Id:     int64(v.ID),
		Url:    v.Url,
		Num:    int64(v.Num),
		Info:   v.Info,
		Status: int64(v.Status),
		Types:  int64(v.Types),
		Image:  v.Image,
		Title:  v.Title,
	}, nil
}

// 视频模糊查询
func (s *Server) VideoShow(_ context.Context, in *__.VideoShowReq) (*__.VideoShowResp, error) {
	var v model.Video
	err := v.GetShow(globar.DB, int(in.Id))
	if err != nil {
		return nil, err
	}
	return &__.VideoShowResp{
		Url:    v.Url,
		Num:    int64(v.Num),
		Info:   v.Info,
		Status: int64(v.Status),
		Types:  int64(v.Types),
		Image:  v.Image,
		Title:  v.Title,
	}, nil
}
